import { useDispatch, useSelector } from 'umi'

import React, { useEffect, useState } from 'react'
import { Table, Tag, Space, Button, Pagination, Input, Select, DatePicker, Modal, Form, Radio, message, Tree } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import style from "./user.css"
import { addRole, updateRole, roleDelete, getMenuById } from '../../apis/system';

const CollectionCreateForm = ({ visible, onCreate, onCancel }) => {
  const [form] = Form.useForm();
  const menu = useSelector((state) => {
    return state.system.menu
  })

  // console.log(111,dept);
  const [expandedKeys, setExpandedKeys] = useState(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState(['0-0-0']);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const onExpand = (expandedKeysValue) => {
    console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.

    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };
  return (
    <Modal
      visible={visible}
      title="新增角色"
      okText="添加"
      cancelText="关闭"
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values, checkedKeys);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item
          name="roleName"
          label="角色名"
          rules={[
            {
              required: true,
              message: '请输入角色名',
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="remark"
          label="描述"

        >
          <Input.TextArea />
        </Form.Item>
        <Form.Item
          name="menuId"


        >


          <Tree
            checkable
            //   onExpand={onExpand}
            //   expandedKeys={expandedKeys}
            //   autoExpandParent={autoExpandParent}
            onCheck={onCheck}
            checkedKeys={checkedKeys}
            onSelect={onSelect}
            selectedKeys={selectedKeys}
            treeData={menu}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default function role() {
  const [data, setData] = useState({ pageSize: 10, pageNum: 1 })
  const [form] = Form.useForm();
  const dispatch = useDispatch()
  const menu = useSelector((state) => {
    return state.system.menu
  })
  // console.log("menu",menu);
  const role = useSelector((state) => {
    return state.system.role
  })

  const getRole = () => {
    dispatch({
      type: 'system/getRoleBySaga',
      data
    })
  }
  const getMenu = () => {
    dispatch({
      type: 'system/getMenuBySaga'
    })
  }
  const getMenuByRole = (id) => {
    dispatch({
      type: 'system/getMenuIdBySaga',
      id
    })
  }
  useEffect(() => {

    getMenu()
    getRole()
    // console.log(users);
  }, [])
  function onChange(current, pageSize) {
    // console.log('Page: ', current, pageSize);
    setData({
      pageSize,
      pageNum: current
    })
    // getUser()
  }
  useEffect(() => {

    getRole()

    // console.log(users);
  }, [data])
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [roleUpdate, setRoleUpdate] = useState({
    menuId: ["1", "2"]
  })
  const [status, setStatus] = useState(false)
  const onCreate = async (values, checkedKeys) => {
    values.menuId = checkedKeys
    // console.log(values);
    const res = await addRole(values)
    // console.log(res);
    message.success('添加成功');

    setVisible(false);
    getRole()
  };

  const onCreate2 = async (values) => {
    
    values.menuId = checkedKeys
    values.roleId=roleUpdate.roleId
    console.log(values);
    const res = await updateRole(values)
    console.log(res);
    message.success('修改成功');
    getRole()



    // setVisible2(false);
  };


  const onFinish = (values) => {
    console.log('Success:', values);
    setData({
      ...data,
      ...values
    })

  };

  const update = async (val) => {

    // roleId
    // getMenuByRole(val.roleId)
    const res = await getMenuById(val.roleId)
    // console.log(res);
    // val.menuId = res
   
    setRoleUpdate(() => {
      return {
        ...val,
        menuId:res
      }
    })
    setStatus(true)
    setVisible2(true)


  }
  const delateRole = async (id) => {
    console.log(id);
    const res = await roleDelete(id)
    // console.log(res);
    message.success('删除成功');
    getRole()

  }
  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      render: text => <a>{text}</a>,
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',

    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
    },


    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <Space size="middle">
          <Button type="dashed" onClick={() => update(text)
          }>修改</Button>
          <Button type="primary" danger onClick={() => delateRole(text.roleId)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];


  const [expandedKeys, setExpandedKeys] = useState(['0-0-0', '0-0-1']);
  const [checkedKeys, setCheckedKeys] = useState(['0-0-0']);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const onExpand = (expandedKeysValue) => {
    console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.

    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };

  const onSelect = (selectedKeysValue, info) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <div>
      <div className={style.box}>

        <Form
          name="basic"
          layout="inline"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 50,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}

          autoComplete="off"
        >
          <Form.Item
            label="角色"
            name="roleName"

          >
            <Input placeholder="请输入角色名" size='middle' />
          </Form.Item>

          <Form.Item
            label="创建日期"
            name="createTimeFrom"

          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit" >
              搜索
            </Button>
          </Form.Item>
        </Form>
        {/* <Button type="primary" icon={<SearchOutlined />} onClick={search}>
            查询
          </Button> */}
        <Button type="primary" onClick={() => {
          setVisible(true);
        }}>新增</Button>
      </div>

      <Table columns={columns} dataSource={role ? role.rows : null} pagination={false} /><br />

      <Pagination showQuickJumper defaultCurrent={1} total={role ? role.total : null} onChange={onChange} showSizeChanger />
      {/* pageSize={data.pageSize} current={data.pageNum} */}


      <CollectionCreateForm
        visible={visible}
        onCreate={onCreate}
        onCancel={() => {
          setVisible(false);
        }}

      />




      <Modal
        visible={visible2}
        title="修改用户"
        okText="修改"
        cancelText="关闭"
        onCancel={() => {
          setVisible2(false);
        }}
        destroyOnClose
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate2(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        修改角色模态
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >
          <Form.Item
            name="roleName"
            label="角色名"
            rules={[
              {
                required: true,
                message: '请输入角色名',
              },
            ]}
          >
            <Input defaultValue={roleUpdate.roleName} />
          </Form.Item>
          <Form.Item
            name="remark"
            label="描述"

          >
            <Input.TextArea defaultValue={roleUpdate.remark} />
          </Form.Item>
          <Form.Item
            name="menuId"


          >

            
            {status? <Tree
              checkable
              //   onExpand={onExpand}
              //   expandedKeys={expandedKeys}
              //   autoExpandParent={autoExpandParent}
              onCheck={onCheck}
            
              onSelect={onSelect}
              selectedKeys={selectedKeys}
              treeData={menu}
              defaultCheckedKeys={roleUpdate.menuId}
            />:null}
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

